@file:JvmName("GsonUtil")
package com.app.baselibrary.ktx
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser

/**
 * 获取json对象
 */
val gson: Gson by lazy { GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
        .serializeNulls()
        .setLenient()
        .setPrettyPrinting()
        .create()
}
/**
 * 实体类转json
 */
val Any.toJson: String
    get() = gson.toJson(this)

/**
 * json转实体类
 */
inline fun <reified T> String.toEntity(): T? {
    return try {
        if (this.isEmpty() || this.isBlank()){
            null
        }else {
            gson.fromJson(this, T::class.java)
        }
    }catch (e: Exception){
        null
    }
}

/**
 * json转集合
 */
inline fun <reified T> String.toList(): List<T> {
    return this.jsonConvertList(T::class.java)
}


/**
 * json转集合
 */
fun <T> String.jsonConvertList(clazz: Class<T>): List<T> {
    return try {
        if (this.isBlank() || this.isEmpty()){
            emptyList()
        }else {
            val elements = JsonParser.parseString(this)
            if (elements.isJsonNull){
                emptyList()
            }else if (elements.isJsonObject || elements.isJsonPrimitive){
                listOf(gson.fromJson(elements, clazz))
            }else {
                val list = ArrayList<T>()
                elements.asJsonArray.forEach {
                    list.add(gson.fromJson(it, clazz))
                }
                list
            }
        }
    }catch (e: Exception){
        emptyList()
    }
}
